An interactive tutorial to find the shortest path on an infinite board.
Beginning from location (0,0), what is the minimum number of steps needed for a knight to get to some other arbitrary location (x,y)?
Constraints: $1 \le x, y \le 8$
This problem asks for the **minimum number of steps**, which immediately suggests a **Breadth-First Search (BFS)**.
A knight moves in an 'L' shape: 2 squares in one direction (horizontal or vertical) and 1 square in the perpendicular direction. From $(0, 0)$, the possible moves are:
For a general graph, Time is $O(V + E)$ (Vertices + Edges). On a chessboard, we can approximate the search space to be the area reachable within the minimum number of steps $M$.
Time: $O(x \cdot y)$ or $O(M^2)$ (approximated search space)
Space: $O(x \cdot y)$ (for the Visited Set and Queue)
function bfs() {
// Queue stores {x, y, steps}
while (queue.length > 0) {
let {x, y, steps} = queue.shift();
if (x === targetX && y === targetY) {
return steps; // Found shortest path!
}
// Explore 8 moves
for (let i = 0; i < 8; i++) {
let nextX = x + DX[i];
let nextY = y + DY[i];
let key = `${nextX},${nextY}`;
if (!visited.has(key)) {
visited.add(key);
queue.push({x: nextX, y: nextY, steps: steps + 1});
}
}
}
}